var enumStyle = {"LIST_SIMPLE":0,"LIST_INDEX":1,"LIST_IMAGE":2,"LIST_DETAIL":3,"LIST_SCORE":4,"GRID_IMAGE":5,"LIST_GOLD":6};

var enumData = {"Name":0,"SUBNAME":1,"IMAGE":2,"IDS":3};

var enumJson = {"images":"getJsonImage","games":"getJsonGame","tygia":"getJsonCurrency","audio":"getJsonAudio",
				"videos":"getJsonVideo","films":"getJsonFilm","weather":"getJsonWeather"};

var domain = "http://210.86.231.120:7001/MOBILE/";
var serverDownload = "http://210.86.231.120:7001/MOBILE/download?";
var serverJson = "http://210.86.231.120:7001/MOBILE/ServiceJsonService";
var serverReftion = "http://JsonUtils/";
var g_userName = "vimic"; //HungNM and vimic
	
var enumMonitor ={ "MIN_SIZE_ICON":60, "MAX_SIZE_ICON":70};	
var g_nSizeIcon = 0;
var g_nInLine = 0;

var g_nHeight = 0;
var g_nWidth = 0;

var g_bGetdata = false;
/*Device phone gap*/

function fadingMsg (locMsg) {
	var aligntop = $(window).scrollTop() + parseInt(g_nHeight*.05);
    $("<div class='ui-overlay-shadow ui-body-e ui-corner-all fading-msg'>" + locMsg + "</div>")
    .css({ "display": "block", "opacity": 0.9, "top": aligntop })
    .appendTo( $.mobile.pageContainer )
    .delay( 1000 )
    .fadeOut( 500, function(){    	
        $(this).remove();
   });
}

function dowloader(url)//"http://vipmobi.net:8089/vi/abc.mp4"
{
	window.plugins.downloader.downloadFile(url, {overwrite: true}, 
		      function(res) {				
				alert(res.status);
	        }, function(error) {
			    alert(error);
		    }
		);
}
function sendSms(number,message)
{
	
	window.plugins.sms.send(number, 
			message,  
		    function () { 
		       alert('Message sent successfully');  
		    },
		    function (e) {
		        alert('Message Failed:' + e);
		    }
		);
}
document.addEventListener("deviceready", onDeviceReady, false);
var uiMgr = new UIManager();
	
function onDeviceReady() 
{	
	uiMgr.Init(); 
	//dowloader();
	//window.plugins.videoPlayer.play("http://stc1-g2.video.zdn.vn/zv/58078113573cfcd32369bbd5862a14be/503bab56/file_uploads/video/2009/12/3/b/1/b10a7718891331b75ad0d090a9dcfadc.mp4");
	document.addEventListener("backbutton", onBackKeyDown, false);
	//document.addEventListener("menubutton", onMenuButton, false);
	if(checkConnection())
	{
		initSizeIcon();	
		//sendSms();
		getJsonData("getJsonCategoryExtend",g_userName,-1,-1,displayHome); //displayHome is call back function
		cordova.exec(null, null, 'CustomSplashScreen', 'hide', []);
	}
	
}

var myMedia = null;
var currentAudio = ''

function onBackKeyDown()
{	
	if(myMedia)
	{
		myMedia.stop();
		myMedia.release();
		myMedia = null;
	}
    if ($.mobile.activePage.attr('id') == 'level0') 
    {   
    	 if (confirm("Bạn có muốn thoát khỏi chương trình?")) {
    		 device.exitApp();
    	 }    	        	
    }
    else 
    {
      history.back(1);
    }
  }
/*
function onMenuButton()
{
	alert("menu");
}
*/
$(document).bind("mobileinit", function () { 
	
	
});


function startDownload(url)
{
	window.open(url,'Download');
}

function processChangePage(title, level, extendId,extendCommand)
{	
	//create new page	
	var sIdPage = "#level"+ parseInt(level);	
	
	if($(sIdPage).length <= 0)
	{		
		createPage("level"+ level,title);
	}
	else
	{
		//Resest title
		var	$header = $(sIdPage).children( ":jqmData(role=header)");
		if($header)
		{
			var sKeyHeader = sIdPage + ' :jqmData(role=header) h1';
			$(sKeyHeader).text(title);
		}
		//remove the content
		var	$content = $(sIdPage).children( ":jqmData(role=content)");
		if($content)
		{					
			$content.html("");
		}
	}
	
	if(extendCommand == -1)
	{				
		getJsonData("getJsonCategoryExtend",g_userName,extendId,level,diplayCategory);
	}
	else if(extendCommand == "title")
	{	
		getListNews("getJsonNews",g_userName,extendId,level,showListNews); 
	}
	else if(extendCommand == "detail")
	{	
		var	$content = $(sIdPage).children( ":jqmData(role=content)");
		if($content)
		{				
			$content.html(extendId);//extendId contain the content
			$.mobile.changePage(sIdPage, {transition: 'pop'});	
		}
	}
	else if(extendCommand == "images")	
	{			
		getListItems("getJsonImage",g_userName,extendId,level,showGridImage); 
	}
	else if (extendCommand == "image")
	{		
		//add the tag image with id 
		var	$header = $(sIdPage).children( ":jqmData(role=header)");
		if($header)
		{
			var sKeyHeader = sIdPage + ' :jqmData(role=header) h1';
			$(sKeyHeader).text(title);
		}
		
		var	$content = $(sIdPage).children( ":jqmData(role=content)");
		if($content)
		{		
			var sAdd = '<img src ="" id="MainImg" ></img>';
			$content.html(sAdd);
			var pRevLeve = parseInt(level) -1;
			var sIdParrent = "#level"+ pRevLeve;
			createSlideShow(sIdParrent,0);	
			$.mobile.changePage(sIdPage, {transition: 'pop'});
			$('body').removeClass('ui-loading');
		}
		
	}
	else if(extendCommand =="videos")
	{
		fadingMsg("Chưa hoàn thành");
		//End loading
		$('body').removeClass('ui-loading');
	}
	else if(extendCommand =="games")
	{
		console.log('games'+extendId +'-'+ level);
		getListItems("getJsonGame",g_userName,extendId,level,showListGame); //test
	}
	else if(extendCommand == "audio")
	{	
		//alert('audio');
		getListItems("getJsonAudio",g_userName,extendId,level,showListAudio); // test
	}	
	else if(extendCommand == "playAudio")
	{
		if(title == "pause")
		{
			if (myMedia != null && extendId != currentAudio)
			 {
				myMedia.stop();
				myMedia.release();
				myMedia = null;
			 }		 
			if(myMedia == null)
			{
				$('body').removeClass('ui-loading');
				myMedia = new Media(serverDownload + extendId);
				var mediaTimer = setInterval(function() {
			        // get media position
			        myMedia.getCurrentPosition(
			            // success callback
			            function(position) {
			                if (position > -1) {
								fadingMsg(position);
			                }
			            },
			            // error callback
			            function(e) {
			                console.log("Error getting pos=" + e);
			            }
			        );
			    }, 3000);
			}
				
			
			 myMedia.play();
			 currentAudio = extendId;
			 $('body').removeClass('ui-loading');
		}
		else if(title == "playing" && myMedia != null)
		{
			if(extendId != currentAudio)
				myMedia.stop();
			else
				myMedia.pause();
		}
				
		 
	}
	else
	{
		fadingMsg("Chưa hoàn thành");
		//End loading
		$('body').removeClass('ui-loading');
	}
	
	//var $page = $(sIdPage);
	//$page.page();
}
/*End init*/
function initSizeIcon()
{	
	if(window.innerHeight !==undefined)
	{
		g_nWidth = window.innerWidth;
		g_nHeight = window.innerHeight;
	}	
	else	// IE
	{ 
		var temp= (document.body.clientWidth)? document.body: document.documentElement;
		g_nWidth = temp.clientWidth;
		g_nHeight = temp.clientHeight;
	}
	
	var nMin = parseInt(g_nWidth/enumMonitor.MAX_SIZE_ICON);
	var nMax = parseInt(g_nWidth/enumMonitor.MIN_SIZE_ICON);
	
	g_nInLine = parseInt((nMin + nMax)/2);
	
	var sizeCell = g_nWidth/g_nInLine;
	//Using 10% for border
	g_nSizeIcon = parseInt(sizeCell*0.7); 	
}

//Utils

function calculateSizeControl(numItem)
{   
	 
	var dimmension;	
	if(window.innerHeight !==undefined)
		dimmension= [window.innerWidth,window.innerHeight]; // most browsers
	else
	{ // IE varieties
		var temp= (document.body.clientWidth)? document.body: document.documentElement;
		dimmension= [temp.clientWidth,temp.clientHeight];	
	}
	
	var width = dimmension[0];
	var Height = dimmension[1];
	
	
	var num = new Number(width);		
	var nSizeBtn = num/(numItem+1);
	var align = num/6;
	var arrInfo=new Array(); 		 // regular array (add an optional integer
	arrInfo[0]= nSizeBtn+ 'px';       // size button
	arrInfo[1]= align + 'px';		
	return arrInfo;
}
//End utils

	
function changDisplay(idPage,header,content,footer,typeRefresh)
{
	
	var $page = $( idPage );
	if($page)
	{
			// Get the header for the page.
		var $header = $page.children( ":jqmData(role=header)" );
			// Get the content area element for the page.
		var	$content = $page.children( ":jqmData(role=content)" );
			// Get the footer area element for the page.
		var	$footer = $page.children( ":jqmData(role=footer)" );
		
		// Find the h1 element in our header and inject the name of
		$header.find( "h1" ).html(header);
		// Inject the category items markup into the content element.
		$content.html( content );
		//Add footer
		$footer.html(footer);
		$page.page();
		// Enhance the control just injected.
		if(typeRefresh == enumStyle.LIST_SIMPLE)
			$content.find( ":jqmData(role=listview)" ).listview();
		// we just loaded.
		//options.dataUrl = urlObj.href;

		// Now call changePage() and tell it to switch to
		// the page we just modified.
		//$.mobile.changePage( $page, options );
	}
}
//End bindingJsM

//GridView
function getIdLevel(sLink)
{
	var vars = [], hash;
	var hashes = sLink.slice(sLink.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[1]);      
    }
    return vars;
}

function createGridIcon(idPage,arrExtendId,arrName,arrICon,arrCommand,numItem,bEmpty)
{
	
	var classBlock = new Array("ui-block-a","ui-block-b","ui-block-c","ui-block-d","ui-block-e");
	var uiGrid = new Array ("ui-grid-a","ui-grid-b","ui-grid-c","ui-grid-d");
	
	if($(idPage) && $(idPage).children( ":jqmData(role=content)"))
	{
		var	$content = $(idPage).children( ":jqmData(role=content)");
		
		var arrInfoMonitor = calculateSizeControl(numItem);
		var nLength = arrExtendId.length;
		var nCount = 0;	
		var sContent = '';
		while(nCount!= nLength)
		{	
			//append fieldset			
			var sField = '<fieldset class='+ uiGrid[numItem-2] +'>';				
			var x = 0;
			var items = ''; 
			var eachLoop = numItem;
			if((nLength - nCount) < numItem)
				eachLoop = nLength - nCount;
			
			for (x =0 ; x < eachLoop; x++)
			{	
				var nLevel = parseInt(idPage.replace("#level",""));	
				var nextLevel = parseInt(nLevel+1);
				var moreInfo = arrName[nCount] +','+nextLevel+','+arrCommand[nCount]+','+arrExtendId[nCount];
				var item = 
				'<div class="'+classBlock[x]+ '">' +					
						'<div >'+
							'<img  src="'+arrICon[nCount] +'"class="center" >'+
							' <span style="display: none;">'+moreInfo+'</span></img>'+								
						'</div>'+
						'<div>'+
							'<p class = "align-text">'+arrName[nCount] +'</p>'+
						'</div>'+					
				'</div> ';
				items = items +item;					
				nCount++;
			}				
			sContent = sContent +(sField + items +'</fieldset>');
		}					
		$content.html(sContent);
		if(sContent.length > 0)
			$.mobile.changePage(idPage, {transition: 'pop'});	
			
		//End loading
		$('body').removeClass('ui-loading');
		
		$(idPage+ ' img').bind("tap",function(event)
		{
			var extendData = $(this).next('span').html();
			console.log(extendData);
			//Get titile name, level, extendId,extendCommand
			var  arrInfo = extendData.split(",");  // title - extendCommand	
			
			$('body').addClass('ui-loading');
			processChangePage(arrInfo[0],arrInfo[1],arrInfo[3],arrInfo[2]);
					
	    });
	}
}

//listView
function populateList(idPage,arrExtendId,arrName,arrCommand,bRefresh) 
{    		
	var $page = $(idPage);
	if($page)    
	{	
		var	$content = $page.children( ":jqmData(role=content)");
		if($content)
		{
			 var $content = $page.children( ":jqmData(role=content)" );	 	     
			  var x;		 
			  var sItems = '<ul  data-filter="false" data-role="listview"  data-theme="c">';
			  for(x in arrName)
			  {
				  
				  var nLevel = parseInt(idPage.replace("#level",""));	
					var nextLevel = parseInt(nLevel+1);
					var moreInfo = arrName[x] +','+nextLevel+','+arrCommand[x]+','+arrExtendId[x];								  
				var item = '<li data-icon="false" >'+
				' <span style="display: none;">'+moreInfo+'</span>'+
				'<p>' +arrName[x] + '</p>'+			
				'</li>';
				
				sItems = sItems + item;
			  }
			  sItems = sItems +'</ul>';
			  $content.html(sItems);	
			  if(sItems.length > 0)
					$.mobile.changePage(idPage, {transition: 'pop'});
				else
					fadingMsg("Không tồn tại dữ liệu");
			  if(bRefresh)
				$content.find( ":jqmData(role=listview)").listview();//must be called if you want the new list elements properly styled
			  
				$('body').removeClass('ui-loading');
				
				$(idPage+ ' li').bind("tap",function(event)
				{
					console.log($(this).html());
					var extendData = $(this).children('span').html();
					console.log(extendData);
					var  arrInfo = extendData.split(",");  // title - extendCommand	
					
					$('body').addClass('ui-loading');
					processChangePage(arrInfo[0],arrInfo[1],arrInfo[3],arrInfo[2]);
							
			    });
		}			
	}
 };
 
 function populateListWithIndex(idPage,arrLink,arrName,bRefresh) 
{    		
	var $page = $(idPage);
	if($page.length > 0)    
	{	
		var	$content = $page.children( ":jqmData(role=content)");
		if($content)
		{
			 var $content = $page.children( ":jqmData(role=content)" );	 	     
			  var x;		 
			  var sItems = '<ul  data-filter="true" data-role="listview"  data-theme="c">';
			  for(x in arrName)
			  {
				  var nLevel = parseInt(idPage.replace("#level",""));	
				var nextLevel = parseInt(nLevel+1);
				var moreInfo = "pause" +','+nextLevel+','+'playAudio'+','+arrLink[x];	
				var item = "<li>" +												
							'<p>'+'<span style="color:darkolivegreen;font-weight:bold">'+x+'.  ' +'</span>' +arrName[x] +'</p>'+
							'<span style ="display:none ">' + moreInfo + ' </span>'+
						'</li>';
				sItems = sItems + item;
			  }
			  sItems = sItems +'</ul>';
			  $content.html(sItems);
			  if(sItems.length > 0)
					$.mobile.changePage(idPage, {transition: 'pop'});
				else
					fadingMsg("Không tồn tại dữ liệu");
			  if(bRefresh)
				$content.find( ":jqmData(role=listview)").listview();//must be called if you want the new list elements properly styled
			  
				$('body').removeClass('ui-loading');
				
				$(idPage+ ' li').bind("tap",function(event)
				{
					console.log($(this).html());
					var $spanObj = $(this).children('span');
					var extendData = $spanObj.html();
					console.log(extendData);
					var  arrInfo = extendData.split(",");  // title - extendCommand	
					var newExtend = '';
					if(arrInfo[0] == 'pause')
					{
						newExtend = 'playing,'+arrInfo[1]+','+arrInfo[2]+','+arrInfo[3];
						$spanObj.html(newExtend);
					}
					else if(arrInfo[0] == 'pause')
					{
						newExtend = 'pause,'+arrInfo[1]+','+arrInfo[2]+','+arrInfo[3];
						$spanObj.html(newExtend);
					}
					$('body').addClass('ui-loading');
					processChangePage(arrInfo[0],arrInfo[1],arrInfo[3],arrInfo[2]);
					
							
			    });			   
		}			
	}
 };

 function CreateListShortView(idPage,arrLink,arrImg,arrShort,arrDate) // include game, lifestyle
 {
	 var $page = $(idPage);
	if($page.length > 0)    
	{
		var	$content = $page.children( ":jqmData(role=content)");
		if($content)
		{
			var items = '<ul  data-filter="false" data-role="listview"  data-theme="c">';
			var i;
		 	for (i in arrLink)
		 	{
		 		var item = 	'<li data-icon="false">'+
		 				'<a href="'+ arrLink[i] +'">'+
		 				'<img src="'+arrImg[i] + '"style=" margin-left: 5px;  margin-top: 5px ; "/> '+
		 				'<h4> '+arrShort[i]+ '</h4>'+
		 				'<p> '+arrDate[i]+'</p>'+					
		 				'</a>'+
		 			'</li>';		 		
		 		items = items + item;		 	
		 	}
		 	items = items + '<ul>';
		 	
		 	$content.html(items);	
		 	if(items.length > 0)
				$.mobile.changePage(idPage, {transition: 'pop'});
			$content.find( ":jqmData(role=listview)").listview();
			
			
		}
	}
	
 	
 }
 function CreateListGames(idPage,arrFile,arrImg,arrShort,arrDate)
 {
	 var $page = $(idPage);
	if($page.length > 0)    
	{
		var	$content = $page.children( ":jqmData(role=content)");
		if($content)
		{
			var items = '<ul  data-filter="false" data-role="listview"  data-theme="c">';
			var i;
		 	for (i in arrFile)
		 	{
		 		var moreInfo = arrFile[i] + ',' + arrShort[i];
		 		var item = 	'<li data-icon="false">'+		 				
		 				'<img src="'+arrImg[i] + '"style=" margin-left: 5px;  margin-top: 5px ; "/> '+
		 				'<h4> '+arrShort[i]+ '</h4>'+
		 				'<p> '+arrDate[i]+'</p>'+	
		 				' <span style="display: none;">'+moreInfo+'</span>'+
		 			'</li>';		 		
		 		items = items + item;		 	
		 	}
		 	items = items + '<ul>';
		 	
		 	$content.html(items);	
		 	if(items.length > 0)
				$.mobile.changePage(idPage, {transition: 'pop'});
			$content.find( ":jqmData(role=listview)").listview();
			
			//End loading
			$('body').removeClass('ui-loading');
			
			$(idPage+ ' li').bind("tap",function(event)
			{
				var extendData = $(this).children('span').html();
				console.log(extendData);
				//Get titile name, level, extendId,extendCommand
				var  arrInfo = extendData.split(",");  // file - name	
				
				//download game
				var linkDownload = serverDownload + arrInfo[0];
				//Send sms
				window.plugins.sms.send('123', 
						'ok',  
					    function () { 
					       //start download  
							 window.plugins.downloader.downloadFile(linkDownload, {overwrite: true}, 
						      function(res) {				
								alert(res.status);
					        }, function(error) {
					        	fadingMsg("file error");
							    alert(error);
						    }
						);
					    },
					    function (e) {
					        alert('Message Failed:' + e);
					    }
					);
						
		    });
			
		}
	}
	 
 }
 function splitContentByLength(str,nLength)
 {
	 var nPart = parseInt(str.length/nLength);
	 var content ='';
	 for(x=0; x < nPart-1 ; x++)
	 {
		 var part = str.substring(x*nLength,(x+1)*nLength);		 
		 content = content + '<p>'+part+'</p>';
		 	
	 }
	 return content + '<p>'+str.substring((nPart-1)*nLength,str.length)+'<p>';
 }
 function CreateListTitleView(idPage,arrImg,arrShort,arrDate,arrCommand,arrContent) 
 {
	 var $page = $(idPage);
	if($page.length > 0)    
	{
		var	$content = $page.children( ":jqmData(role=content)");
		if($content)
		{
			var sizeImage = parseInt(g_nSizeIcon*0.5);
			var items = '<ul  data-filter="false" data-role="listview"  data-theme="c">';
			var i;
		 	for (i in arrShort)
		 	{
		 		var nLevel = parseInt(idPage.replace("#level",""));	
				var nextLevel = parseInt(nLevel+1);
				var moreInfo = arrShort[i] +','+nextLevel+','+arrCommand[i]+','+arrContent[i];
				
		 		var item = 	'<li data-icon="false">'+		 				
		 				'<img src="'+arrImg[i] + ' "/> '+
		 					splitContentByLength(arrShort[i],25)+
		 				'<p style="color:orange"> '+arrDate[i]+'</p>'+
		 				' <span style="display: none;">'+moreInfo+'</span>'+		 				
		 			'</li>';		 		
		 		items = items + item;		 	
		 	}
		 	items = items + '<ul>';
		 	
		 	$content.html(items);	
		 	if(items)
	 		{		 		
		 		$.mobile.changePage(idPage, {transition: 'pop'});					
	 		}
		 	else
				fadingMsg("Không tồn tại dữ liệu");
		 	
		 	$content.find( ":jqmData(role=listview)").listview();//must be called if you want the new list elements properly styled
			  
			$('body').removeClass('ui-loading');
			
			$(idPage+ ' li').bind("tap",function(event)
			{
				var extendData = $(this).children('span').html();
				console.log(extendData);
				
				var  arrInfo = extendData.split(",");  // title - extendCommand	
				
				$('body').addClass('ui-loading');
				processChangePage(arrInfo[0],arrInfo[1],arrInfo[3],arrInfo[2]);
						
		    });
						
		}
	}
 	
 }

function createListGold(id,arrCenter,arrCode,arrDataNew,arrDataOld)
{
	var items = '<ul data-role="listview" data-filter="false">';
	var i;
	for (i in arrCenter)
	{
		var item = '<li>' +
				   '<div class="head">'+arrCenter[i]+'</div>' +
				   '<div data-role="navbar" >'+
					'<ul>'+
						'<li><p style="border-right:2px solid green">'+arrCode[i]+'</p></li>'+
						'<li><p style="border-right:2px solid green">'+arrDataNew[i]+'</p></li>'+
						'<li><p>'+arrDataOld[i]+'</p></li>'+
					'</ul>'+
				'</div>'+
				'</li>';
		items = items + item;		
		
	}
	items = items + '</ul>';
	$(id).append(items);
}
function createListViewScore(id,date,arrNameLeft,arrNameRight,arrImgLeft,arrImgRight) 
{
	var items = '<ul data-role="listview" data-filter="false" data-theme="b">';
	
	var i;
	for (i in arrNameLeft)
	{
		var item = '<li>'+
				'<div class="head_score">'+ date + '</div>'+						
				'<center>'+
					'<table style="margin-left: 10">'+
						'<tr>'+
							'<td style="text-align:left; width: 20">'+arrNameLeft[i]+'</td>'+
							'<td><img src="'+arrImgLeft[i]+'"/></td>'+
							'<td> -::- </td>'+
							'<td><img src="'+arrImgRight[i]+'"/></td>'+
							'<td style="text-align:right; width: 20">'+arrNameLeft[i]+'</td>'+			 		
						'</tr>'+
					'</table>'+
				'</center>'+
				'<p style="text-align: center;  font-size: 10px">Ngay17/06/2013</p>'+
			'</li>';
			items = items + item;
	}
	items = items + '</ul>';
	$(id).append(items);
}
//End listView

//vimic


	function createPage(id,title)
	{		
		var page = '<div data-role="page" id="' + id +'">'+
		'<div data-role="header" data-theme="b"  data-position="fixed" >'+
			'<h1>'+title +'</h1>'+'</div>'+
		'<div data-role="content">'+
		'</div>'+
		//'<div data-role="footer" data-theme="b"></div>'+
	'</div>';		
		$('body').append(page);
	}
	
	
	
	
	function createFolderInLocal()
	{
		function onError(e){
			   alert("ERROR");
			    console.log(JSON.stringify(e));
			}
		function gotDir(d)
		{	
		    DATADIR = d;
		    var reader = DATADIR.createReader();
		    reader.readEntries(function(d)
		    {
		             
		    },onError);
		}
		
		function onFSSuccess(fileSystem)
		{
			fileSystem.root.getDirectory("Android/data/vimic.home",{create:true},gotDir,onError);
		}
		
		window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSSuccess, null); 
	}
	function displayHome(nLevel,jSondata)
	{	
		 
		createFolderInLocal();
		var arrExtendId = new Array();
		var arrName = new Array();
		var arrImage = new Array();
		var arrCommand = new Array();
		var ncount = 0;
		while(1)
		{
			if(jSondata[ncount] == null)
				break;
			arrName[ncount] = jSondata[ncount].extendName;
			arrImage[ncount] = serverDownload +jSondata[ncount].extendIcon + '&w='+g_nSizeIcon + '&h='+g_nSizeIcon+'&v=1';			
			arrExtendId[ncount] =jSondata[ncount].extendId; //'#category?id='+jSondata[ncount].extendId+'&level=0';
			arrCommand[ncount] = jSondata[ncount].extendCommand;		
			ncount ++;			
			//save image into phone
		}			
		createGridIcon("#level0",arrExtendId,arrName,arrImage,arrCommand,g_nInLine,false,false);
	}
	function diplayCategory(nLevel,jSondata)
	{
		//function createGridImage(id,arrLink,arrName,arrImage,numItem,bRefresh)	
		var arrExtendId = new Array();
		var arrName = new Array();
		var arrImage = new Array();
		var arrCommand = new Array();
		var ncount = 0;
		var bHasImg = false;
		while(1)
		{
			if(jSondata[ncount] == null)
				break;
			arrName[ncount] = jSondata[ncount].extendName;
			arrImage[ncount] = serverDownload +jSondata[ncount].extendIcon + '&w=' + g_nSizeIcon+'&h=' + g_nSizeIcon+'&v=1';
			if(bHasImg == false && jSondata[ncount].extendIcon)
				bHasImg = true;
			if(jSondata[ncount].extendCommand == 'title')
				arrExtendId[ncount] = jSondata[ncount].categoryId
			else
				arrExtendId[ncount] = jSondata[ncount].extendId;
			arrCommand[ncount] = jSondata[ncount].extendCommand;
			ncount ++;
		}
		if(ncount > 0)
		{	
			//console.log(ncount);
		  var parentId = jSondata[0].parentId;		 
		  var idpage = "#level" + nLevel;
		  if(bHasImg)
			createGridIcon(idpage,arrExtendId,arrName,arrImage,arrCommand,g_nInLine,false,true);
		  else
			populateList(idpage,arrExtendId,arrName,arrCommand,true);
		}
		else
		{		
			$('body').removeClass('ui-loading');		
			fadingMsg("Không tồn tại dữ liệu");
		}
	}
	function viewHTML(content)
	{
	}
	
	var imgs = null;	
	var imageIndex = 0;
	function slideImage(bIncrease)
	{
		$("#MainImg").fadeOut("slow", function() {
			
			var temp = imgs[imageIndex].src.split("&");
			var realImg = temp[0]+"&w=" +g_nWidth;	
	        $(this).attr("src", realImg).fadeIn("fast");
	        if(bIncrease)
        	{
	        	++imageIndex;
	        	if(imageIndex>=imgs.length)
		            imageIndex=0;
        	}	      
	        else
        	{
	        	--imageIndex;
	        	if(imageIndex<=0)
		            imageIndex=imgs.length-1;
        	}
	        	
	        
	    });
	}
	
	$('#MainImg').live('swiperight', function() { 
		
		 slideImage(true);
		return false;
    });
	
	$('#MainImg').live('swipeleft', function() { 
		
		 slideImage(false);
		return false;
   });
	
	function createSlideShow(idPage,nIndex)
	{
		//get link url of image	
		
		if($(idPage).length > 0)
		{			
			imgs = $(idPage).find('img');		
			if(imgs.length > 0)
			{
				var temp = imgs[nIndex].src.split("&");			
				var realImg = temp[0]+"&w=" +g_nWidth;				
				$("#MainImg").attr("src", realImg);
				imageIndex = nIndex;
			}
						
		}

		
	}
	function createGridImage(idPage,arrLink,arrName,arrImage,arrCommand,numItem,bRefresh,bEmpty)
	{
		var classBlock = new Array("ui-block-a","ui-block-b","ui-block-c","ui-block-d","ui-block-e");
		var uiGrid = new Array ("ui-grid-a","ui-grid-b","ui-grid-c","ui-grid-d","ui-grid-e");
		var $page = $(idPage);
		if($page.length == 0)
			alert("not exist page:" + idPage);
		var	$content = $page.children( ":jqmData(role=content)");
		if($content)
		{
			var arrInfoMonitor = calculateSizeControl(numItem);
			var nLength = arrLink.length;
			var nCount = 0;	
			var sContent ='';
			while(nCount!= nLength)
			{	
				//append fieldset				
				var sField = '<fieldset class='+ uiGrid[numItem-2] +'>';				
				var x = 0;
				var items = ''; 
				var eachLoop = numItem;
				if((nLength - nCount) < numItem)
					eachLoop = nLength - nCount;
				
				for (x =0 ; x < eachLoop; x++)
				{	
					
					var nLevel = parseInt(idPage.replace("#level",""));	
					var nextLevel = parseInt(nLevel+1);
					var moreInfo = arrName[nCount] +','+nextLevel+','+arrCommand[nCount]+','+arrLink[nCount];
					var item = 
					'<div class="'+classBlock[x]+ '">' +						
						'<div >'+
							'<img  src="'+arrImage[nCount] +'" class="center" >'+
							' <span style="display: none;">'+moreInfo+'</span></img>'+								
						'</div>'+
						'<div>'+
							'<p class = "align-text">'+arrName[nCount] +'</p>'+
						'</div>'+						
					'</div> ';
					items = items +item;					
					nCount++;
				}	
				var sEndField = '</fieldset>';
				sContent = sContent + (sField + items +sEndField);				
			}				
			$content.html(sContent);	
			
			if(sContent.length > 0)
				$.mobile.changePage(idPage, {transition: 'pop'});	
				
			//End loading
			$('body').removeClass('ui-loading');
			
			$(idPage+ ' img').bind("tap",function(event)
			{
				var extendData = $(this).next('span').html();
				console.log(extendData);
				//Get titile name, level, extendId,extendCommand
				var  arrInfo = extendData.split(",");  // title - extendCommand	
				
				$('body').addClass('ui-loading');
				processChangePage(arrInfo[0],arrInfo[1],arrInfo[3],arrInfo[2]);
						
		    });
		}		
	}
	
	function showGridImage(nLevel,jSondata)
	{
		var arrLink = new Array();
	  var arrName = new Array();
	  var arrImage = new Array();
	  var arrExtends = new Array();
	  var ncount = 0;
	  while(1)
		{
			if(jSondata[ncount] == null)
				break;
			arrName[ncount] =""; //jSondata[ncount].imageName;
			
			arrImage[ncount] = serverDownload +jSondata[ncount].imageIcon + '&w='+ g_nSizeIcon+ '&h='+ g_nSizeIcon;
			var nextLevel = parseInt(nLevel) + 1;
			arrLink[ncount] = '#category?id='+jSondata[ncount].extendId + '&level='+nextLevel;
			arrExtends[ncount] = jSondata[ncount].titleCommand;
            	
			ncount ++;
		}
		if(ncount > 0)
		{           
    		var extendId = jSondata[0].extendId;
   		    var idContent = "#level" + nLevel;		 
    		createGridImage(idContent,arrLink,arrName,arrImage,arrExtends,g_nInLine,false,true);
    		$(idContent).live('swiperight', function() { 
    			
    			fadingMsg('swiperight');
    			return false;
    	    });
    		
    		$(idContent).live('swipeleft', function() { 
    			
    			fadingMsg('swipeleft');
    			return false;
    	   });
        }
		else
		{
            alert("group is empty");
        }
	}
	
	function showListNews(nLevel,jSondata)
	{
		var arrLink = new Array();
		  var arrName = new Array();	 
		  var arrDate = new Array();
		  var arrImg = new Array();
		  var arrCommand = new Array();
		  var arrContent = new Array();
		  var ncount = 0;
		  while(1)
			{
				if(jSondata[ncount] == null)
					break;
				arrName[ncount] = jSondata[ncount].titleName;				
				arrImg[ncount] = serverDownload + jSondata[ncount].titleIcon;
				var nextLevel = parseInt(nLevel) +1;				
				//CONVERT DATE
				var miliseconds = Number(jSondata[ncount].submit);				
				var d = new Date(miliseconds);				
				arrDate[ncount] = d.getDate() +'/'+ d. getMonth() +'   ' + d.getMinutes()+':'+d.getHours();
				
				arrCommand[ncount] = jSondata[ncount].titleCommand;
				
				arrContent[ncount] = jSondata[ncount].contentList[0].contentData;				
				ncount ++;
			}
			if(ncount > 0)
			{			
	    		var extendId = jSondata[0].titleId;
	   		    var idPage = "#level" + nLevel;				
	   		    CreateListTitleView(idPage,arrImg,arrName,arrDate,arrCommand,arrContent);	    		
	        }
			else
			{
	            alert("group is empty");
	        }
	}
	
	function showListGame(nLevel,jSondata)
	{
		  var arrFile = new Array();
		  var arrName = new Array();	 
		  var arrDate = new Array();
		  var arrImg = new Array();
		  var ncount = 0;
		  while(1)
			{
				if(jSondata[ncount] == null)
					break;
				arrName[ncount] = jSondata[ncount].gameName;
				arrImg[ncount] = serverDownload +jSondata[ncount].gameIcon + '&w='+ g_nSizeIcon;
				arrFile[ncount] = jSondata[ncount].gameFile;				
				
				var miliseconds = Number(jSondata[ncount].submit);				
				var d = new Date(miliseconds);				
				arrDate[ncount] = d.getDate() +'/'+ d. getMonth() +'   ' + d.getMinutes()+':'+d.getHours();
				ncount ++;
			}
			if(ncount > 0)
			{
				//alert(nLevel);
	    		var extendId = jSondata[0].extendId;
	   		    var idPage = "#level" + nLevel;
				//alert("ok");	
	   		    CreateListGames(idPage,arrFile,arrImg,arrName,arrDate);	    		
	        }
			else
			{
				$('body').removeClass('ui-loading');		
				fadingMsg("Không tồn tại dữ liệu");
	        }
	}
	function showListAudio(nLevel,jSondata)
	{
	  
	  var arrLink = new Array();
	  var arrName = new Array();	 
	  var arrDate = new Array();
	  var ncount = 0;
	  while(1)
		{
			if(jSondata[ncount] == null)
				break;
			arrName[ncount] = jSondata[ncount].audioName;
			arrLink[ncount] =  jSondata[ncount].audioUrl;
			
			//CONVERT DATE
			var miliseconds = Number(jSondata[ncount].audioCreate);				
			var d = new Date(miliseconds);				
			arrDate[ncount] = d.getDate() +'/'+ d. getMonth() +'   ' + d.getMinutes()+':'+d.getHours();			
			ncount ++;
		}
		if(ncount > 0)
		{			
   		    var idPage = "#level" + nLevel;				
    		populateListWithIndex(idPage,arrLink,arrName,true);
        }
		else
		{
			$('body').removeClass('ui-loading');		
			fadingMsg("Không tồn tại dữ liệu");
        }
	}

//End vimic

//WebServices


function checkConnection()
 {
	var networkState = navigator.network.connection.type;

	var states = {};
	states[Connection.UNKNOWN]  = 'Unknown connection';
	states[Connection.ETHERNET] = 'Ethernet connection';
	states[Connection.WIFI]     = 'WiFi connection';
	states[Connection.CELL_2G]  = 'Cell 2G connection';
	states[Connection.CELL_3G]  = 'Cell 3G connection';
	states[Connection.CELL_4G]  = 'Cell 4G connection';
	states[Connection.NONE]     = 'No network connection';		
	if(networkState == Connection.WIFI || 
	networkState == Connection.CELL_3G ||
	networkState == Connection.CELL_4G)
		return true;
	
	else
	{	
		alert('Current connect'+states[networkState]+'you must connect to internet');
		if (navigator.app && navigator.app.exitApp) 
		{
		    navigator.app.exitApp();
		} else if (navigator.device && navigator.device.exitApp) 
		{
		    navigator.device.exitApp();
		}
		return false;
	}
}
	
function connectServer(sServer)
{
	//if(checkConnection()== false)
	//	return null;
	var xmlHttp = new XMLHttpRequest();
	xmlHttp.open("POST", sServer,true);
	//UNSENT (numeric value 0) The object has been constructed.
	//OPENED (numeric value 1) The open() method has been successfully invoked
	//HEADERS_RECEIVED (numeric value 2) 
	//LOADING (numeric value 3)
	//DONE (numeric value 4) 
	//http://www.w3.org/TR/XMLHttpRequest/#dom-xmlhttprequest-opened
	if(xmlHttp.readyState == 1) //opened
		return xmlHttp;
	else
	{
		xmlHttp.abort();
		return null;
	}		
}	
function getListNews(sMessage,user,ExtendId,nLevel,callback)
{
	var xmlhttp = connectServer(serverJson);
	if( xmlhttp == null)
		alert("can't connect to server");
		
xmlhttp.onreadystatechange=function() 
{	
 if (xmlhttp.readyState == 4)
	{	
		var sXml ="<?xml version='1.0' encoding='UTF-8'?>";
		var sSoap = '<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><ns2:'+sMessage+'Response xmlns:ns2="http://JsonUtils/"><return>';
		
		var tailRemove = '</return></ns2:'+sMessage+'Response></S:Body></S:Envelope>';
					
		var sReponse = xmlhttp.responseText;			
		sReponse = sReponse.replace(sXml,'');
		sReponse = sReponse.replace(sSoap,'');
		 
		sReponse = sReponse.replace(tailRemove,''); 			
		var JsonString = '{ "objectJson" :' + sReponse + '}';			
		var obj = eval("("+JsonString+")");				
		if(obj)
		{	
			callback(nLevel,obj.objectJson) ;
		}	
		else
			alert("can't load database");
	}
}
xmlhttp.setRequestHeader("Content-Type", "text/xml;charset=UTF-8");  		
var xml = 
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' +'xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' + 
   '<soap:Body> ' +
   '<'+sMessage+' xmlns="http://JsonUtils/"> ' +
	  '<datetime xmlns="" />'+
	  '<categoryId xmlns="">'+ExtendId+'</categoryId>'+
	  '<titleName xmlns="" />'+
	  '<username xmlns="" />'+
	  '<minRow xmlns="">0</minRow>'+
	  '<maxRow xmlns="">2</maxRow>'+
	'</'+sMessage+'> ' +
   '</soap:Body> ' +
 '</soap:Envelope>';	 
xmlhttp.send(xml);
}
function getListItems(sMessage,user,ExtendId,nLevel,callback) 
 {       
	var xmlhttp = connectServer(serverJson);
		if( xmlhttp == null)
			alert("can't connect to server");
			
	xmlhttp.onreadystatechange=function() 
	{	
	 if (xmlhttp.readyState == 4)
		{	
			var sXml ="<?xml version='1.0' encoding='UTF-8'?>";
			var sSoap = '<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><ns2:'+sMessage+'Response xmlns:ns2="http://JsonUtils/"><return>';
			
			var tailRemove = '</return></ns2:'+sMessage+'Response></S:Body></S:Envelope>';
						
			var sReponse = xmlhttp.responseText;			
			sReponse = sReponse.replace(sXml,'');
			sReponse = sReponse.replace(sSoap,'');
			 
			sReponse = sReponse.replace(tailRemove,''); 			
			var JsonString = '{ "objectJson" :' + sReponse + '}';			
			var obj = eval("("+JsonString+")");				
			if(obj)
			{	
				callback(nLevel,obj.objectJson) ;
			}	
			else
				alert("can't load database");
		}
	}
	xmlhttp.setRequestHeader("Content-Type", "text/xml;charset=UTF-8");  		
	var xml = 
	'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' +'xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' + 
	   '<soap:Body> ' +
		 '<'+sMessage+' xmlns="http://JsonUtils/"> ' +
		 '<extendName xmlns="" />'+
		  '<prefixCode xmlns="" />'+
		  '<extendId xmlns="">'+ExtendId+'</extendId>'+		  
		  '<username xmlns="">'+user+'</username>'+		  
		  '<status xmlns="">1</status>'+
		  '<minRow xmlns="">0</minRow>'+
	      '<maxRow xmlns="">10</maxRow>'+
		 '</'+sMessage+'> ' +
	   '</soap:Body> ' +
	 '</soap:Envelope>';	 
	xmlhttp.send(xml);   
 } 
 
function getJsonBySql(sSQL,minRow,maxRow,callback) 
{
	var xmlhttp = connectServer(serverJson);
	if( xmlhttp == null)
		alert("can't connect to server");
	 	
	xmlhttp.onreadystatechange=function() 
	{	
	 if (xmlhttp.readyState == 4)
		{	
		 $.mobile.hidePageLoadingMsg();
			var sXml ="<?xml version='1.0' encoding='UTF-8'?>";
			var sSoap = '<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><ns2:'+sMessage+'Response xmlns:ns2="http://JsonUtils/"><return>';
			
			var tailRemove = '</return></ns2:'+sMessage+'Response></S:Body></S:Envelope>';
						
			var sReponse = xmlhttp.responseText;			
			sReponse = sReponse.replace(sXml,'');
			sReponse = sReponse.replace(sSoap,'');
			 
			sReponse = sReponse.replace(tailRemove,''); 			
			var JsonString = '{ "Jsons" :' + sReponse + '}';
			var obj = null;
			if(sReponse != "")
			 obj = eval("("+JsonString+")");				
			if(obj)
			{	
				callback(obj.Jsons) ;
			}	
			else
				alert("can't load database");
		}
	}
	xmlhttp.setRequestHeader("Content-Type", "text/xml;charset=UTF-8");  		
	var xml = 
	'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' +'xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' + 
	   '<soap:Body> ' +
		 '<'+sMessage+' xmlns="http://JsonUtils/"> ' +		 
		  '<sql xmlns="">'+ sSQL +'</sql>'+		  
		  '<minRow xmlns="">' + minRow + '</minRow>'+
		  'maxRow xmlns="">' + maxRow + '</maxRow>'+
		  '<nativeQuery>true</nativeQuery>'+
		 '</'+sMessage+'> ' +
	   '</soap:Body> ' +
	 '</soap:Envelope>';
	xmlhttp.send(xml); 
}
function getJsonData(sMessage,user,parrentId,nLevel,callback) 
 {     	
	var xmlhttp = connectServer(serverJson);
		if( xmlhttp == null)
			alert("can't connect to server");
		
	$('body').addClass('ui-loading'); 	
	xmlhttp.onreadystatechange=function() 
	{	
		
	 if (xmlhttp.readyState == 4)
		{			 
		 	//if($("#splash"))
			//{
			//	$("#splash").attr("src", $("#splash").src).fadeIn("slow");
			//}
		 
			var sXml ="<?xml version='1.0' encoding='UTF-8'?>";
			var sSoap = '<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><ns2:'+sMessage+'Response xmlns:ns2="http://JsonUtils/"><return>';
			
			var tailRemove = '</return></ns2:'+sMessage+'Response></S:Body></S:Envelope>';
						
			var sReponse = xmlhttp.responseText;			
			sReponse = sReponse.replace(sXml,'');
			sReponse = sReponse.replace(sSoap,'');
			 
			sReponse = sReponse.replace(tailRemove,''); 			
			var JsonString = '{ "Jsons" :' + sReponse + '}';
			var obj = null;
			if(sReponse != "")
			 obj = eval("("+JsonString+")");				
			if(obj)
			{	
				callback(nLevel,obj.Jsons) ;
			}	
			else
			{
				//Load from local
				if(1)
				{
					
				}
				else
					device.exitApp();
			}				
		}
	}
	xmlhttp.setRequestHeader("Content-Type", "text/xml;charset=UTF-8");  		
	var xml = 
	'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' +'xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' + 
	   '<soap:Body> ' +
		 '<'+sMessage+' xmlns="http://JsonUtils/"> ' +
		 '<extendName xmlns="" />'+
		  '<prefixCode xmlns="" />'+
		  '<parentId xmlns="">'+parrentId+'</parentId>'+		  
		  '<username xmlns="">'+user+'</username>'+		  
		  '<status xmlns="">1</status>'+
		 '</'+sMessage+'> ' +
	   '</soap:Body> ' +
	 '</soap:Envelope>';
	xmlhttp.send(xml);   
 } 
//End WebServices

